//
//  OauthViewController.swift
//  新浪微博01
//
//  Created by 李国伟 on 15/12/8.
//  Copyright © 2015年 李国伟. All rights reserved.
//

import UIKit
import SVProgressHUD
class OauthViewController: UIViewController {

    private lazy var webView = UIWebView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        webView.loadRequest(NSURLRequest(URL: NetworkTools.sharedTools.oauthURL))
    }
    
    override func loadView() {
        view = webView
        webView.delegate = self
        title = "登录新浪微博"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "back")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "autoFill")
    }
    
    //销毁控制器
   @objc private func back(){
    //取消
    SVProgressHUD.dismiss()
    dismissViewControllerAnimated(true, completion: nil)
    }
    
    //自动填充
    @objc private func autoFill()
    {
        //里面填写js文件
        let js = "document.getElementById('userId').value = '15095185209';" +
        "document.getElementById('passwd').value = 'a35265131';"
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
}


///  MARK: 代理方法
extension OauthViewController: UIWebViewDelegate{
    
    /// 将要加载请求的代理方法
    /// - parameter webView:        webView
    /// - parameter request:        将要加载的请求
    /// - parameter navigationType: navigationType，页面跳转的方式
    ///
    /// - returns: 返回 false 不加载，返回 true 继续加载
    /// 如果 iOS 的代理方法中有返回 bool，通常返回 true 很正常，返回 false 不能正常工作
    
    //最终目的拦截百度，跳转到我们自己的页面
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //确保回调页面是百度
        guard let url = request.URL where url.host == "www.baidu.com" else{
          
            //继续下一条请求
            return true
        }
        
        //对get数据，进行解析
        guard let query = url.query where query.hasPrefix("code=") else{
//            back()
            print("取消授权")
            return false
        }
        
        //获取到授权吗
        let code = url.query?.substringFromIndex("conde".endIndex)
        
        //获取令牌
        UserAccountViewModel.shareModel.loadToken(code!) { (isSuccess) -> () in
            
            if isSuccess == false{
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(2.0 * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), { () -> Void in
                    self.back()
                })
                print("出错了")
            }else{
                //销毁访客控制器跳转到主控制器
               self.dismissViewControllerAnimated(false, completion: { () -> Void in
                SVProgressHUD.dismiss()
                NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootViewControllerNotification, object: "hello world", userInfo: nil)
               })
            }
        }
        return false
    }
}

//加载web过程中的加载图标变化
extension OauthViewController{
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        
        if error?.code == 102{
            SVProgressHUD.dismiss()
        }else{
            SVProgressHUD.showInfoWithStatus("您的网络不给力")
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(2.0 * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), { () -> Void in
                self.back()
            })
        }
    }
}